package golo

import "C"
import (
	"unsafe"
)

//#cgo CFLAGS: -I${SRCDIR}/lib
//#cgo LDFLAGS: -L${SRCDIR}/lib -ldll-test
//#include "dll-test.h"
import "C"

/*
C语言预测结果结构体转换为Go预测结果结构体
*/
func (infer *C.InferResult) toGo() (InferResult, error) {
	result := InferResult{
		recognition_size: int(infer.recognition_size),
		file_name:        C.GoString(infer.file_name),
		recognition_list: make([]Recognition, infer.recognition_size, infer.recognition_size),
	}
	// 将指针转换为切片
	recognition_list := unsafe.Slice(infer.recognition_list, result.recognition_size)
	for i := 0; i < result.recognition_size; i++ {
		result.recognition_list[i] = Recognition{
			rect: Rect{
				x:      int(recognition_list[i].rect.x),
				y:      int(recognition_list[i].rect.y),
				width:  int(recognition_list[i].rect.width),
				height: int(recognition_list[i].rect.height),
			},
			confidence: result.recognition_list[i].confidence,
			tag_name:   C.GoString(recognition_list[i].tag_name),
		}
	}

	return result, InferResultErrMap[C.int(infer.err)]
}

/*识别文件，返回识别结果*/
func Infer(filename string) (*InferResult, error) {
	var result *C.InferResult = C.Infer(C.CString(filename))
	// 释放指针指向的对象
	defer C.DeleteInferResult(result)
	inferResult, err := result.toGo()
	return &inferResult, err
}
